package com.itjiange.controller;

import com.itjiange.common.BaseResponse;
import com.itjiange.common.ErrorCode;
import com.itjiange.constant.CommonConstant;
import com.itjiange.constant.UserConstant;
import com.itjiange.exception.BusinessException;
import com.itjiange.model.dto.*;
import com.itjiange.model.pojo.User;
import com.itjiange.model.vo.UserCurrentVo;
import com.itjiange.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 用户接口
 *
 * @author ItJiange
 * @date 2023/10/27
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Value("${myServer.otherPath}")
    private String basePath;

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     *
     * @param userLoginDto
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginDto userLoginDto, HttpServletRequest request) {
        if (userLoginDto == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 解析参数
        String userAccount = userLoginDto.getUserAccount();
        String password = userLoginDto.getPassword();
        String verCode = userLoginDto.getVerCode();
        return userService.login(userAccount, password, verCode, request);
    }

    /**
     * 当前登录用户信息
     *
     * @return
     */
    @GetMapping("/currentUser")
    public BaseResponse<UserCurrentVo> currentUser(HttpServletRequest request) {
        HttpSession requestSession = request.getSession();
        User currentUser = (User) requestSession.getAttribute(UserConstant.USER_STATUS);
        UserCurrentVo userCurrentVo = new UserCurrentVo();
        BeanUtils.copyProperties(currentUser, userCurrentVo);
        return new BaseResponse<>(CommonConstant.SUCCESS, userCurrentVo);
    }

    /**
     * 用户退出登录
     *
     * @param request
     * @return
     */
    @GetMapping("/loginOut")
    public BaseResponse<String> userLoginOut(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate();
        return new BaseResponse<>(CommonConstant.SUCCESS, "退出登录成功！");
    }

    /**
     * 用户注册
     *
     * @param userRegisterDto
     * @param request
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Integer> register(@RequestBody UserRegisterDto userRegisterDto, HttpServletRequest request) {
        if (userRegisterDto == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterDto.getUserAccount();
        String password = userRegisterDto.getPassword();
        String checkPassword = userRegisterDto.getCheckPassword();
        String verCode = userRegisterDto.getVerCode();
        return userService.register(userAccount, password, checkPassword, verCode, request);
    }

    /**
     * 修改用户信息
     *
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody UserUpdateDto userUpdateDto, HttpServletRequest request) {
        BaseResponse<Integer> updateResult = userService.update(userUpdateDto, request);
        HttpSession session = request.getSession();
        if (CommonConstant.SUCCESS == updateResult.getCode()) {
            session.removeAttribute(UserConstant.USER_STATUS);
        }
        return updateResult;
    }

    /**
     * 头像上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<String> upload(MultipartFile file, HttpServletRequest request) {
        // file 是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        log.info(file.toString());

        // 原始文件名
        String originalFilename = file.getOriginalFilename();

        // 创建一个目录对象
        File dir = new File(basePath);
        // 判断当前目录是否存在
        if (!dir.exists()) {
            // 目录不存在，需要创建
            dir.mkdirs();
        }

        // 将头像路径存入数据库
        String avatarUrl = basePath + File.separator + originalFilename;
        userService.updateUserAvatar(avatarUrl, request);

        // 将临时文件转存到指定位置
        try {
            file.transferTo(new File(avatarUrl));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BaseResponse<>(CommonConstant.SUCCESS, "头像上传成功", originalFilename);
    }

    /**
     * 获取用户登录信息
     * @param request
     * @return
     */
    @GetMapping("/getUserMessage")
    public BaseResponse<User> getUserMessage(HttpServletRequest request) {
        return userService.getUserMessage(request);
    }

    /**
     * 所有用户
     *
     * @return
     */
    @GetMapping("/all")
    public BaseResponse<List<User>> allUsers() {
        return userService.getAllUser();
    }

    /**
     * 删除指定用户
     *
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public BaseResponse<Integer> deleteUserById(@PathVariable int id) {
        return userService.deleteUserById(id);
    }

    /**
     * 分页查询
     *
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/page/{currentPage}/{pageSize}")
    public BaseResponse<List<User>> selectUsersByPage(@PathVariable int currentPage, @PathVariable int pageSize) {
        return userService.getUsersByPage(currentPage, pageSize);
    }

    /**
     * 获取用户总数
     *
     * @return
     */
    @GetMapping("/count")
    public BaseResponse<Integer> getUsersCount() {
        return userService.getAllUsersCount();
    }

    /**
     * 获取查询条件
     *
     * @return
     */
    @PostMapping("/condition")
    public BaseResponse<List<User>> getUsersByCondition(@RequestBody UserQueryDto userQueryDto) {
        return userService.getUsersByCondition(userQueryDto);
    }

}
